package com.example.demoplus.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.demoplus.R;
import com.example.demoplus.bean.FoodBean;

import java.util.ArrayList;
import java.util.List;


public class MenuAdapter extends BaseAdapter {
    private Context context;
    private List<FoodBean> beans = new ArrayList<FoodBean>();

    public MenuAdapter(Context context) {
        this.context = context;
    }
//    设置数据
    public void setData(List<FoodBean> foodBeans){
        this.beans.clear();
        this.beans.addAll(foodBeans);
//        刷新数据
        notifyDataSetChanged();

    }

    @Override
    public int getCount() {
        return beans.size();
    }

    @Override
    public Object getItem(int position) {
        return beans.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null){
//            加载布局
            convertView = LayoutInflater.from(context).inflate(R.layout.menu_item, null);
            viewHolder = new ViewHolder();
            viewHolder.tvFoodName = convertView.findViewById(R.id.tv_food_name);
            viewHolder.tvTaste = convertView.findViewById(R.id.tv_taste);
            viewHolder.tvSaleNum = convertView.findViewById(R.id.tv_sale_nu);
            viewHolder.tvPrice = convertView.findViewById(R.id.tv_price);
            viewHolder.btnAddCar = convertView.findViewById(R.id.btn_add_car);
            viewHolder.ivFoodPic = convertView.findViewById(R.id.iv_food_pic);
//            放入数据到布局里
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder)convertView.getTag();
        }
//        根据位置填充数据
        FoodBean foodBean = beans.get(position);
//      Log.d("twm","foodBean"+foodBean);
        if (foodBean != null){
            viewHolder.tvFoodName.setText(foodBean.getFoodName());
            viewHolder.tvTaste.setText(foodBean.getTaste());
            viewHolder.tvSaleNum.setText("月售"+foodBean.getSaleNum());
            viewHolder.tvPrice.setText("￥"+foodBean.getPrice());
            Glide.with(context).load(foodBean.getFoodPic()).error(R.mipmap.ic_launcher).into(viewHolder.ivFoodPic);
        }
        return convertView;
    }
    class ViewHolder{
        public TextView tvFoodName, tvTaste, tvSaleNum, tvPrice;
        public Button btnAddCar;
        public ImageView ivFoodPic;
    }
}
